package com.application.fabric.test.ca_become;


import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.security.CryptoSuiteFactory;
import org.hyperledger.fabric_ca.sdk.EnrollmentRequest;
import org.hyperledger.fabric_ca.sdk.HFCAClient;

import java.nio.file.Paths;
import java.util.Properties;

public class tls注册 {
    public static void main(String[] args) throws Exception {
        /*创建ca客户端*/
        Properties pros = new Properties();
        /*往客户端添加组织1的根证书文件 并且取名
        * */
        pros.put("pemFile","src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem");
        pros.put("allowAllHostNames","true");

        /*然后拿着这个客户端去找组织的端口 例如说这是组织1的根证书我们要去找7054端口  实例化*/
        HFCAClient caClient = HFCAClient.createNewInstance("https://localhost:7054",pros);
        /*获取加密套 进行加密*/
        CryptoSuite cryptoSuite = CryptoSuiteFactory.getDefault().getCryptoSuite();
        /*客户端加密*/
        caClient.setCryptoSuite(cryptoSuite);

        /*创建钱包这个钱包是用来管理身份id的*/
        Wallet wallet = Wallets.newFileSystemWallet(Paths.get("src/main/java/com/application/fabric/test/query/application/wallet"));

        /*检查管理员是否在 在的hua那就没必要去进行注册了*/
        if (wallet.get("admin") != null) {
            System.out.println("An identity for the admin user \"admin\" already exists in the wallet");
        }

        /*那么获取路径以后我们就需要去进行注册操作了 简单说可以把操作分为与fabric账本交互 然后填身份id*/
        /*TLS证书 这东西是管理员凭证*/
        final EnrollmentRequest enrollmentRequestTLS= new EnrollmentRequest();
        /*添加主机号 这边使用本地开发我们填写的是localhost*/
        enrollmentRequestTLS.addHost("localhost");
        /*设置文件类型*/
        enrollmentRequestTLS.setProfile("tls");

        /*注册*/
        Enrollment enrollment = caClient.enroll("admin", "adminpw", enrollmentRequestTLS);
        /*下面这行代码就很常见 x509私钥生成 对象为org1 --组织1与注册信息(证书)enrollment*/
        Identity user = Identities.newX509Identity("Org1MSP",enrollment);
        /*钱包内容注入取名*/
        wallet.put("admin",user);
        System.out.println("管理员注册成功");
    }
}
